package com.ljkj.zjf.rest;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MultivaluedMap;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import com.alibaba.fastjson.JSON;
import com.ljkj.common.db.util.GlobalSeterUtil;
import com.ljkj.common.db.util.UUID;
import com.ljkj.zjf.common.GlobalNames;

@Path("rest/upload")
public class UploadFileResource{

	private final String UPLOADED_FILE_PATH = GlobalSeterUtil.getString("img_path"); 
	
	@POST  
    @Path("/file")  
    //@Consumes("multipart/form-data")
	public String uploadFile(@Context HttpServletRequest request){
		
		Map<String, Object> errorMap = new HashMap<String, Object>();
		errorMap.put("errCode", GlobalNames.CALL_RESULT_FAIL);
		
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator fileIterator = null;
		try {
			fileIterator = upload.getItemIterator(request);
		} catch (FileUploadException e) {
			e.printStackTrace();
			errorMap.put("errMsg", e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			errorMap.put("errMsg", e.getMessage());
		}
        try {
        	String fileName = "";
        	if(fileIterator.hasNext()){
        		while (fileIterator.hasNext()) {
    			    FileItemStream item = fileIterator.next();
    			    if ("file_upload".equals(item.getFieldName())){
    			        byte[] content = IOUtils.toByteArray(item.openStream());
    			        String jpgName = UUID.getUUID()+".jpg";
    			        fileName = UPLOADED_FILE_PATH + jpgName;  
    			        writeFile(content,fileName);  
    			        
    			        errorMap.put("errCode", GlobalNames.CALL_RESULT_SUCC);
    			        errorMap.put("errMsg", "/zjf_img/"+jpgName);
    			        break;
    			    }
    			}
        	}else{
        		errorMap.put("errMsg", "未获取到上传的图片");
        	}
			
		} catch (FileUploadException e) {
			e.printStackTrace();
			errorMap.put("errMsg", e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			errorMap.put("errMsg", e.getMessage());
		}
        return JSON.toJSONString(errorMap);
    } 
   
    private String getFileName(MultivaluedMap<String, String> header) {  
        String[] contentDisposition = header.getFirst("Content-Disposition").split(";");  
       for (String filename : contentDisposition) {  
            if ((filename.trim().startsWith("filename"))) {  
                String[] name = filename.split("=");  
                String finalFileName = name[1].trim().replaceAll("\"", "");  
                return finalFileName;  
            }  
        }  
        return "unknown";  
    }  
   
    //save to somewhere  
    private void writeFile(byte[] content, String filename) throws IOException {  
        File file = new File(filename);  
        if (!file.exists()) {  
            file.createNewFile();  
        }  
        FileOutputStream fop = new FileOutputStream(file);  
        fop.write(content);  
        fop.flush();  
        fop.close();  
   }  

}
